package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     *  根据条件查询当前用户下所有的地址簿列表
     * @param addressBook
     * @return
     */
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     *  新增地址簿
     * @param addressBook
     */
    public void save(AddressBook addressBook) {
        //新增地址的时候，要设置这个地址所属人的id，并且新增地址时，要设置当前地址不是默认地址
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Transactional
    public void setDefault(AddressBook addressBook) {
        //首先先将当前用户的所有地址改为非默认地址，不要单将默认地址的那条数据该，sql语句太麻烦，性能不好
        // update address_book set is_default = 0 where user_id = ?

        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //将当前地址改为默认地址
        // update address_book set is_default = 1 where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     *  根据id查询地址簿信息
     * @param id
     * @return
     */
    public AddressBook getAddressBookById(Long id) {
//        AddressBook addressBook = new AddressBook();
//        addressBook.setUserId(BaseContext.getCurrentId());
//        addressBook.setId(id);

        //其实这里不要userId作为条件查询也许，因为地址Id是唯一的，查出来的地址也是唯一的，
        // 所以不用使用userId作为条件查询，否则会造成性能缺失
        return addressBookMapper.getAddressBookById(id);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     *  删除地址
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }


}
